<h1>{{#if article.id}}编辑文章{{else}}添加文章{{/if}}</h1>

<form action="/admin/articles{{#if article.id}}/{{article.id}}{{/if}}" method="post" id="articleForm">
    {{#if article.id}} <input type="hidden" name="_method" value="put" />{{/if}}
    <div class="mb-3">
        <label for="title" class="form-label">标题</label>
        <input type="text" class="form-control" id="title" name="title" value="{{article.title}}">
    </div>
    <div class="mb-3">
        <label for="title" class="form-label">内容</label>
        <div id="editor">
          {{{article.content}}}
        </div>
        <input type="hidden" name="content" id="contentInput" />
    </div>
    <div class="mb-3">
        <label for="title" class="form-label">分类</label>
        <div id="categoryTree" class="border rounded p-3"></div>
    </div>
    <div class="mb-3">
        <label for="title" class="form-label">标签</label>
        <div class="d-flex flex-wrap">
            {{#each tags}}
                <div class="form-check me-3 mb-2">
                    <input 
                        class="form-check-input" 
                        type="checkbox" 
                        name="tagIds" 
                        value="{{this.id}}"
                        {{#if (contains (mapToIds ../article.tags) this.id)}}checked{{/if}}
                    >

                    <label class="form-check-label">{{this.name}}</label>
                </div>
            {{/each}}
        </div>
    </div>
    <div class="mb-3">
        <label for="status" class="form-label">状态</label>
        <select class="form-control" name="status" id="status">
            <option value="1" {{#if article.status}}selected{{/if}}>激活</option>
            <option value="0" {{#unless article.status}}selected{{/unless}}>未激活</option>
        </select>
    </div>
    <button type="submit" class="btn btn-primary">保存</button>
</form>
<script>
			const {
				ClassicEditor,
				Essentials,
				Paragraph,
				Bold,
				Italic,
				Font,
        Image,
        ImageToolbar,
        ImageUpload,
        ImageResize,
        ImageStyle,
        // SimpleUploadAdapter,
        Plugin,
			} = CKEDITOR;
      async function getSignature(filename){
        const res = await fetch(`/admin/cos-signature?key=${encodeURIComponent(filename)}`)
        return res.json()
      }
      class COSUploadAdptor {
        constructor(loader) {
          this.loader = loader
        }
        async upload(){
          const file = await this.loader.file
          const signature = await getSignature(file.name)
          const {sign,key,buchet,region} = signature
          // nest-1316737134.cos.ap-guangzhou.myqcloud.com
          // nest-1316737134.cos.ap-guangzhou.myqcloud.com/
          // nest-1316737134.cos.ap-guangzhou.myqcloud.com/111.png
          // nest111-1316737134.cos.ap-guangzhou.myqcloud.com/%E8%81%94%E6%83%B3%E6%88%AA%E5%9B%BE_20241208160329.png
          // nest-1316737134.cos.ap-guangzhou.myqcloud.com/%E8%81%94%E6%83%B3%E6%88%AA%E5%9B%BE_20241208203325.png
          const url = `https://${buchet}.cos.${region}.myqcloud.com/${key}`
          return fetch(url, {
            method: 'put',
            headers: {Authorization: sign},
            body: file
          }).then((res) => {
            return {
              default: res.url
            }
          })
        }
      }
      class COSUploadAdptorPlugin extends Plugin {
        static get requires() {
          return [ImageUpload]
        }
        init() {
          this.editor.plugins.get('FileRepository').createUploadAdapter = (fileLoader) => new COSUploadAdptor(fileLoader)
        }
      }
			// Create a free account and get <YOUR_LICENSE_KEY>
			// https://portal.ckeditor.com/checkout?plan=free
			ClassicEditor
				.create( document.querySelector( '#editor' ), {
					plugins: [ 
            Essentials, Paragraph, Bold, Italic, Font,  
            Image,
            ImageToolbar,
            ImageUpload,
            ImageResize,
            ImageStyle,
            COSUploadAdptorPlugin // 换远程服务
             // SimpleUploadAdapter 
            ],
          image: {
            toolbar: ['imageTextAlternative', 'imageStyle:side', 'resizeImage:50','resizeImage:75', 'resizeImage:original']
          },
					toolbar: [
						'undo', 'redo', '|', 'bold', 'italic', '|',
						'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', '|', 'insertImage'
					],
          //simpleUpload: {
          //  uploadUrl: '/admin/upload'
          //}
				} )
				.then( editor => {
					const form = document.getElementById('articleForm')
          const contentInput = document.getElementById('contentInput')
          form.addEventListener('submit', () => {
            contentInput.value = editor.getData()
          })
				} )
				.catch( error => {
					console.error( error );
				} );
		</script>
<script>
    const categoryTree = {{{json categoryTree}}}
    const selectedCategoryIds = {{{mapToIds article.categories}}}
    function renderTree(categories){
        let html = `<ul class="list-unstyled">`
        
        categories.forEach(function (category) {
            html+= `
                <li class="mb-2">
                    <div class="d-flex align-items-center">
                    ${category.children?.length>0?`<span class="toggle me-2 cursor-pointer"><i class="bi bi-folder-minus"></i></span>`:'<span class="me-4"></span>'}
                        <label class="form-check-label">
                            <input type="checkbox" class="form-check-input" ${selectedCategoryIds.includes(category.id)?'checked' :''} name="categoryIds" value="${category.id}" />
                            ${category.name}
                        </label>
                    </div>
                        ${category.children?.length>0?`<div class="children ms-4">${renderTree(category.children)}</div>`: ''}
                    
                </li>
            `
        })
        html += '</ul>'
        return html
    }
    $(function () {
        $('#categoryTree').html(renderTree(categoryTree))
        function hideChildren($tr, id){
            const $children = $tr.nextAll(`tr[data-parent="${id}"]`)
            $children.each(function(){
                const childId = $(this.data('id'))
                hideChildren($(this), childId)
            })
            $children.hide()
        }
        $('body').on('click', '.togger', function () {
            const children = $(this).parent().siblings('.children')
            if (children.is('.visible')) {
                children.hide()
                $(this).html('<i class="bi bi-folder-plus"></i>')
            } else {
                children.show()
                $(this).html('<i class="bi bi-folder-minus"></i>')
            }
        })
    })
</script>